package com.kestrel.space.core.controller;

import com.kestrel.space.common.controller.BaseController;
import com.kestrel.space.common.utils.Result;
import com.kestrel.space.core.service.CosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author yebolin
 * @date 2024/8/26
 */
@RestController
@RequestMapping("cos")
public class CosController extends BaseController {
    @Autowired
    private CosService cosService;

    /**
     * 上传文件
     * @param file
     */
    @RequestMapping("upload")
    public Result upload(@RequestParam MultipartFile file) throws Exception {
        String originalFileName = file.getOriginalFilename();
        String type = null;
        if (originalFileName!= null) {
            int dotIndex = originalFileName.lastIndexOf('.');
            if (dotIndex > 0 && dotIndex < originalFileName.length() - 1) {
                type = originalFileName.substring(dotIndex + 1);
            }
        }
        String upload = cosService.upload(file, type, getUser());
        if(upload.equals("文件上传失败")){
            return Result.fail("文件上传失败");
        }
        return Result.ok(upload);
    }

    /**
     * 下载文件
     * @param fileUrl
     */
    @RequestMapping("download")
    public void download(@RequestParam String fileUrl) {
        cosService.download(fileUrl, request, response);
    }

    /**
     * 删除文件
     * @param fileUrl
     */
    @RequestMapping("delete")
    public Result delete(@RequestParam String fileUrl) {
        String delete = cosService.delete(fileUrl);
        if(delete.equals("文件删除失败")){
            return Result.fail("文件删除失败");
        }
        return Result.ok(delete);
    }

    /**
     * 定时删除cos中（被逻辑删超过1个月的数据）
     */
    @RequestMapping("scheduledDelete")
    public Result scheduledDelete(){
        return Result.ok("定时删除成功");
    }
}
